<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let set = new Set(['red', 'green', 'blue']);
    for (let item of set.keys()) {
      console.log(item, 'item'); // 挨个打印出来
    }
    // keys和values返回的内容一致，因为set没有键
    for (let item of set.values()) {
      console.log(item, 'item'); // 挨个打印出来
    }

    // entries返回的是键名和值名，每次输出一组，两个成员完全一致
    for (let item of set.entries()) {
      console.log(item, 'item'); // ['red', 'red'] ['green', 'green'] ['blue', 'blue']
    }

    // set自身默认就是可以遍历的
    console.log(Set.prototype[Symbol.iterator] === Set.prototype.values, 'Set.prototype'); // true

    // Set结构实例和数组一样，也拥有forEach方法
    set.forEach((value, key) => {
      console.log(value, 'value'); // red
      console.log(key, 'key'); // red
    })

    // 扩展运算符可以去重 -- 默认内部使用for of
    let set1 = new Set(['red', 'green', 'blue', 'red'])
    let arr1 = [...set1]
    console.log(arr1, 'arr1');

    // set间接使用map
    let arr2 = [...new Set([1,2,3])].map(item => item * 2)
    let set2 = new Set(arr2)
    console.log(set2); // 2 4 6的set

    // set间接使用filter
    let arr3 = [...new Set([1,2,3])].filter(item => item <= 2)
    console.log(arr3, 'arr3');
    let set3 = new Set(arr3)
    console.log(set3, 'set3'); // 1 2的set

    // 并集
    let a = new Set([1,2,3])
    let b = new Set([2,3,4])
    let union = new Set([...a, ...b])
    console.log(union, 'union');

    // 交集
    let intersect = new Set(
      [...a].filter(item => b.has(item))
    )
    console.log(intersect, 'intersect'); // 2 3是交集

    // a相对于b的差集
    let difference = new Set(
      [...a].filter(item => !b.has(item))
    )
    console.log(difference, 'difference'); // 1 去除了 2 3

    // 没有直接的方法改变原来的set结构
    let c = new Set([1,2,3])
    c = new Set([...c].map(item => item * 2))
    console.log(c, 'c'); // {2, 4, 6}

    c = new Set(Array.from(c, val => val * 3))
    console.log(c, 'c'); // {6, 12, 18}
  </script>
</body>
</html>